<template>
  <el-button type="primary" @click="onButton()">{{ btnText }}</el-button>
  <el-dialog
    v-model="swipeVerifyDialogVisible"
    title="请完成安全验证"
    width="355px"
  >
    <SwipeVerify
      ref="swipeVerifyInstance"
      :imgs="images"
      @success="onSwipVerifySuccess"
    ></SwipeVerify>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref } from 'vue';
import imgUrl from '@/assets/varify.jpg';
import { SwipeVerify, SwipeVerifyInstance } from 'vue3-swipe-verify';
import 'vue3-swipe-verify/dist/style.css';
import { ElMessage } from 'element-plus';
import { shios } from '@/api/Shios';
import { Search } from '@element-plus/icons-vue';
const props = defineProps({
  mobileNumber: { type: String, required: true },
});

function onButton() {
  if (!/^1[3456789]\d{9}$/.test(props.mobileNumber)) {
    ElMessage.error(`手机号错误! (手机号:${props.mobileNumber})`);
    return;
  }
  swipeVerifyDialogVisible.value = true;
}
// #region 图形验证
const swipeVerifyDialogVisible = ref(false);
const images = [imgUrl];
const swipeVerifyInstance = ref<SwipeVerifyInstance>();
/**
 * 图形验证
 */
function onSwipVerifySuccess() {
  SendSmsVcode();
  swipeVerifyDialogVisible.value = false;
  swipeVerifyInstance.value?.refresh();
}
// #endregion
// #region 发送验证码
const btnText = ref('发送验证码');
const disabled = ref(false);
async function SendSmsVcode() {
  const { data } = await shios.post<SendStatus>('sms/send', {
    search: { mobileNumber: props.mobileNumber },
  });
  if (data?.code == 'Ok') {
    ElMessage.success('发送成功');
    countdown();
  } else {
    ElMessage.success(`发送失败! (手机号 ${props.mobileNumber})`);
  }
}
const time = ref(60);
/**
 * 验证码倒数计时
 */
function countdown() {
  // 1.时间开始倒数
  // 2.按钮进入禁用状态
  // 3.如果倒计时结束 按钮恢复可用状态 按钮文字变为重新发送, 时间重置
  // 4.倒计时的过程中 按钮文字为 多少s后重新发送
  let timer = setInterval(() => {
    time.value--;
    btnText.value = `${time.value}s 后重发`;
    disabled.value = true;
    if (time.value === 0) {
      disabled.value = false;
      btnText.value = '重新发送';
      time.value = 60;
      clearInterval(timer);
    }
  }, 1000);
}
// #endregion
</script>

<style lang="scss" scoped></style>
